import { useState, useEffect, useRef } from 'react'
import { Container, Card, Button, Alert, Spinner } from 'react-bootstrap'
import { ToastContainer, toast } from 'react-toastify'
import axios from 'axios';
import './App.css'
import ServerBasicConfig from './components/ServerBasicConfig';
import GameExperienceSettings from './components/GameExperienceSettings';
import SecuritySettings from './components/SecuritySettings';
import PerformanceAndFileConfig from './components/PerformanceAndFileConfig';
import ModManagement from './components/ModManagement';
import TimeSettings from './components/TimeSettings';
import AnnouncementDisplay from './components/AnnouncementDisplay';
import LogManagement from './components/LogManagement';


// AdvancedSettings 组件已删除
import AnnouncementSettings from './components/AnnouncementSettings';
import BasicSettings from './components/BasicSettings';

// 配置axios默认URL
axios.defaults.baseURL = 'http://localhost:5000';

function App() {
  const [activeTab, setActiveTab] = useState('basic')
  const [config, setConfig] = useState({})
  const [initialConfig, setInitialConfig] = useState({})
  const [unsavedChangesCount, setUnsavedChangesCount] = useState(0)
  const [serverStatus, setServerStatus] = useState('unknown')
  const [loading, setLoading] = useState(false)
  const [availableMods, setAvailableMods] = useState([])
  const [serverStartTime, setServerStartTime] = useState(null)

  const fadeInRef = useRef(null)

  // 获取服务器状态指示器的CSS类名
  const getStatusIndicatorClass = () => {
    if (serverStatus === 'running') return 'status-indicator running'
    if (serverStatus === 'stopped') return 'status-indicator stopped'
    if (serverStatus === 'paused') return 'status-indicator paused'
    return 'status-indicator unknown'
  }

  // 检查服务器状态
  const checkServerStatus = async () => {
    setLoading(true)
    try {
      const response = await axios.get('/api/server/status')
      const status = response.data.data
      
      if (!status.running) {
        setServerStatus('stopped')
        setServerStartTime(null)
      } else if (status.paused) {
        setServerStatus('paused')
      } else {
        setServerStatus('running')
        // 设置服务器启动时间
        if (status.startTime) {
          setServerStartTime(new Date(status.startTime))
        }
      }
    } catch (error) {
      console.error('获取服务器状态失败:', error)
      toast.error('获取服务器状态失败: ' + (error.response?.data?.message || error.message))
    } finally {
      setLoading(false)
    }
  }

  // 启动服务器
  const startServer = async () => {
    setLoading(true)
    try {
      const response = await axios.post('/api/server/start')
      toast.success('服务器启动中...')
      setTimeout(() => {
        checkServerStatus()
      }, 5000)
    } catch (error) {
      console.error('启动服务器失败:', error)
      let errorMessage = '启动服务器失败'
      if (error.response) {
        if (error.response.status === 400 && error.response.data?.message === 'Server is already running') {
          errorMessage = '服务器已经在运行中'
        } else {
          errorMessage = `启动服务器失败: ${error.response.data?.message || `HTTP错误 ${error.response.status}`}`
        }
      } else if (error.request) {
        errorMessage = '无法连接到服务器'
      }
      toast.error(errorMessage)
    } finally {
      setLoading(false)
    }
  }

  // 停止服务器
  const stopServer = async () => {
    setLoading(true)
    try {
      await axios.post('/api/server/stop')
      toast.success('服务器停止中...')
      setTimeout(() => {
        checkServerStatus()
      }, 3000)
    } catch (error) {
      console.error('停止服务器失败:', error)
      toast.error('停止服务器失败')
    } finally {
      setLoading(false)
    }
  }

  // 加载配置
  const loadConfig = async () => {
    setLoading(true)
    try {
      const response = await axios.get('/api/config')
      const rawData = response.data.data || response.data || {};
      
      setConfig(rawData)
      setInitialConfig(JSON.parse(JSON.stringify(rawData)))
      setUnsavedChangesCount(0)
      toast.success('配置加载成功')
    } catch (error) {
      console.error('加载配置失败:', error)
      toast.error('加载配置失败')
    } finally {
      setLoading(false)
    }
  }
  
  // 比较当前配置和初始配置，计算未保存的参数数量
  const countUnsavedChanges = (current, initial) => {
    const deepEqual = (a, b) => {
      if (a === b) return true;
      
      if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') {
        return false;
      }
      
      if (Array.isArray(a) && Array.isArray(b)) {
        if (a.length !== b.length) return false;
        for (let i = 0; i < a.length; i++) {
          if (!deepEqual(a[i], b[i])) return false;
        }
        return true;
      }
      
      if (Array.isArray(a) !== Array.isArray(b)) {
        return false;
      }
      
      const keysA = Object.keys(a);
      const keysB = Object.keys(b);
      
      if (keysA.length !== keysB.length) {
        return false;
      }
      
      for (const key of keysA) {
        if (!keysB.includes(key) || !deepEqual(a[key], b[key])) {
          return false;
        }
      }
      
      return true;
    };
    
    let count = 0;
    const allKeys = new Set([...Object.keys(current), ...Object.keys(initial)]);
    
    for (const key of allKeys) {
      const inCurrent = key in current;
      const inInitial = key in initial;
      
      if (inCurrent !== inInitial) {
        count++;
      } else if (inCurrent && inInitial) {
        if (!deepEqual(current[key], initial[key])) {
          count++;
        }
      }
    }
    
    return count;
  };

  // 保存配置
  const saveConfig = async () => {
    setLoading(true)
    try {
      await axios.post('/api/config', config)
      setInitialConfig(JSON.parse(JSON.stringify(config)))
      setUnsavedChangesCount(0)
      toast.success('配置保存成功')
    } catch (error) {
      console.error('保存配置失败:', error)
      if (error.response) {
        if (error.response.status === 400) {
          const errorData = error.response.data
          if (errorData.errors && Array.isArray(errorData.errors)) {
            const errorMessage = errorData.errors.join('\n')
            toast.error(`配置验证失败:\n${errorMessage}`, {
              position: 'top-right',
              autoClose: 8000,
              closeOnClick: true
            })
          } else {
            toast.error('配置验证失败: ' + (errorData.message || '数据格式错误'))
          }
        } else {
          toast.error('保存配置失败: ' + (error.response.data?.message || error.message))
        }
      } else {
        toast.error('网络错误，请检查连接后重试')
      }
    } finally {
      setLoading(false)
    }
  }

  // 组件挂载时初始化
  useEffect(() => {
    const initData = async () => {
      try {
        const response = await axios.get('/api/config')
        const rawData = response.data.data || response.data || {}
        setConfig(rawData)
        setInitialConfig(JSON.parse(JSON.stringify(rawData)))
      } catch (error) {
        console.error('无法从服务器加载配置:', error)
        setConfig({})
        setInitialConfig({})
      }
    }
    
    initData()
    checkServerStatus()
    
    if (fadeInRef.current) {
      fadeInRef.current.classList.add('fade-in-complete')
    }
  }, [])

  // 监听配置变化，更新未保存参数计数
  useEffect(() => {
    if (Object.keys(initialConfig).length > 0) {
      const count = countUnsavedChanges(config, initialConfig)
      setUnsavedChangesCount(count)
    }
  }, [config, initialConfig])

  // 定时刷新模组目录
  useEffect(() => {
    const fetchAvailableMods = async () => {
      if (serverStatus !== 'running' && serverStatus !== 'paused') {
        try {
          const response = await axios.get('/api/read-mods-folder');
          if (response.data.success && response.data.mods) {
            setAvailableMods(prevMods => {
              if (JSON.stringify(prevMods) !== JSON.stringify(response.data.mods)) {
                return response.data.mods;
              }
              return prevMods;
            });
          }
        } catch (error) {
          console.error('获取可用模组失败:', error);
        }
      }
    };

    fetchAvailableMods();
    
    let refreshInterval;
    if (serverStatus !== 'running' && serverStatus !== 'paused') {
      refreshInterval = setInterval(fetchAvailableMods, 5000);
    }
    
    return () => {
      if (refreshInterval) {
        clearInterval(refreshInterval);
      }
    };
  }, [serverStatus]);

  // 渲染当前活动的标签页内容
  const renderActiveTab = () => {
    switch (activeTab) {
      case 'basic':
        return <ServerBasicConfig config={config} setConfig={setConfig} />;
      case 'game':
        return <GameExperienceSettings config={config} setConfig={setConfig} />;
      case 'logs':
        return <LogManagement config={config} setConfig={setConfig} />;
      case 'mission':
        return <AnnouncementDisplay config={config} setConfig={setConfig} />;
      case 'mods':
        return (
          <ModManagement 
            config={config}
            setConfig={setConfig}
            availableMods={availableMods}
            serverStatus={serverStatus}
          />
        );

      case 'performance':
        return <PerformanceAndFileConfig config={config} setConfig={setConfig} />;
      case 'security':
        return <SecuritySettings config={config} setConfig={setConfig} />;
      case 'time':
        return <TimeSettings config={config} setConfig={setConfig} />;
      case 'advanced':
        return null; // 高级设置组件已删除，此处不再渲染
      default:
        return <ServerBasicConfig config={config} setConfig={setConfig} />;
    }
  };

  return (
    <Container fluid className="App p-0">
      <ToastContainer position="top-right" autoClose={3000} />
      
      <div className="main-content">
        <div ref={fadeInRef} className="w-100">
          <Card className="mb-4 fade-in border-3 shadow-medium" style={{borderColor: '#d32f2f', boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3)'}}>
            <Card.Body className="p-3" style={{backgroundColor: 'var(--secondary-color)'}}>
              <h2 className="text-center mb-0" style={{color: 'var(--primary-color)', textShadow: '0 2px 10px rgba(0,0,0,0.5)', fontWeight: 'bold'}}>DAYZ服务器管理器</h2>
            </Card.Body>
          </Card>
          
          <div className="row">
            {/* 左侧导航栏 */}
            <div className="col-md-3 slide-in d-flex flex-column">
              <Card className="border-3 shadow-medium mb-2" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(15px)', borderColor: '#d32f2f', boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 0 10px rgba(211, 47, 47, 0.2)'}}>
                <Card.Body style={{padding: '0px'}}>
                  <div className="p-3" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(20px)', border: '1px solid rgba(255, 255, 255, 0.1)'}}>
                  <Button 
                    variant={serverStatus === 'running' ? 'danger' : 'success'} 
                    onClick={serverStatus === 'running' ? stopServer : startServer}
                    disabled={loading}
                    className="w-100 mb-2"
                    style={{color: '#ffffff', minHeight: '40px'}}
                  >
                    {loading ? <Spinner animation="border" size="sm" /> : (serverStatus === 'running' ? '停止服务器' : '启动服务器')}
                  </Button>

                  <Button 
                    variant="info" 
                    onClick={loadConfig}
                    disabled={loading}
                    className="w-100 mb-2"
                    style={{color: '#ffffff'}}
                  >
                    {loading ? <Spinner animation="border" size="sm" /> : '重载配置'}
                  </Button>
                  <Alert 
                    variant="info" 
                    className="w-100 text-center mb-2 cursor-pointer p-2 d-flex align-items-center justify-content-center"
                    onClick={checkServerStatus}
                    style={{color: '#000000', border: 'none', height: '40px'}}
                  >
                    <span className={getStatusIndicatorClass()}></span>
                    状态: {serverStatus === 'running' ? '启动' : serverStatus === 'stopped' ? '停止' : serverStatus === 'paused' ? '暂停' : '未知'}
                  </Alert>
                  
                  {serverStartTime && (
                    <div className="w-100 text-center mb-2 p-2 d-flex align-items-center justify-content-center"
                      style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(20px)', border: '1px solid rgba(255, 255, 255, 0.1)', height: '40px'}}
                    >
                      启动时间: {serverStartTime.toLocaleString()}
                    </div>
                  )}
                </div>
                </Card.Body>
              </Card>
              <Card className="flex-grow-1 border-3 shadow-medium" style={{backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(15px)', borderColor: '#d32f2f', boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3), inset 0 0 10px rgba(211, 47, 47, 0.2)'}}>
                  <Card.Header style={{backgroundColor: 'rgba(40, 40, 40, 0.7)', backdropFilter: 'blur(15px)'}}>
                    <h5 className="mb-0" style={{color: '#ffffff', fontWeight: 'bold'}}>控制面板</h5>
                  </Card.Header>
                  <div className="list-group mb-0 h-100 d-flex flex-column" style={{backgroundColor: 'transparent', border: 'none'}}>
                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'basic' ? 'active' : ''}`}
                    onClick={() => setActiveTab('basic')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    服务器基础配置
                  </button>
                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'game' ? 'active' : ''}`}
                    onClick={() => setActiveTab('game')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    游戏体验设置
                  </button>
                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'security' ? 'active' : ''}`}
                    onClick={() => setActiveTab('security')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    安全与反作弊设置
                  </button>
                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'performance' ? 'active' : ''}`}
                    onClick={() => setActiveTab('performance')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    性能与文件配置
                  </button>

                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'time' ? 'active' : ''}`}
                    onClick={() => setActiveTab('time')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    时间设置
                  </button>

                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'mission' ? 'active' : ''}`}
                    onClick={() => setActiveTab('mission')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    公告显示
                  </button>
                  
                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'mods' ? 'active' : ''}`}
                    onClick={() => setActiveTab('mods')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    模组管理
                  </button>
                  <button 
                    className={`list-group-item list-group-item-action ${activeTab === 'logs' ? 'active' : ''}`}
                    onClick={() => setActiveTab('logs')}
                    style={{color: '#ffffff', backgroundColor: 'rgba(26, 26, 26, 0.6)', backdropFilter: 'blur(10px)', borderColor: 'rgba(255, 255, 255, 0.1)'}}
                  >
                    日志管理
                  </button>

                </div>
              </Card>
            </div>
            
            {/* 右侧内容区域 */}
            <div className="col-md-9 fade-in" style={{position: 'relative'}}>
              {/* 右上角悬浮保存配置按钮 */}
              <div style={{position: 'absolute', top: '20px', right: '20px', zIndex: 100}}>
                <Button 
                  variant="primary" 
                  onClick={saveConfig}
                  disabled={loading}
                  className={`btn-hover-effect save-button-float ${unsavedChangesCount > 0 ? 'btn-blinking' : ''}`}
                  style={{
                    backgroundColor: '#d32f2f',
                    borderColor: '#d32f2f',
                    boxShadow: unsavedChangesCount > 0 
                      ? '0 0 30px rgba(211, 47, 47, 1), 0 4px 16px rgba(0, 0, 0, 0.3)' 
                      : '0 0 20px rgba(211, 47, 47, 0.8), 0 4px 16px rgba(0, 0, 0, 0.3)',
                    transition: 'box-shadow 0.3s ease'
                  }}
                >
                  {loading ? 
                    <Spinner animation="border" size="sm" /> : 
                    unsavedChangesCount > 0 ? 
                    `保存配置:${unsavedChangesCount}个参数未保存` : 
                    '保存配置'
                  }
                </Button>
              </div>
              
              {/* 动态渲染当前标签页内容 */}
              {renderActiveTab()}
            </div>
          </div>
        </div>
      </div>
      
      {/* 页面底部悬浮使用说明按钮 */}
      <div style={{position: 'fixed', bottom: '20px', right: '20px', zIndex: 9999, display: 'block'}}>
        <div 
          style={{position: 'relative'}}
          onMouseEnter={(e) => {
            const tooltip = e.currentTarget.querySelector('.tooltip-content');
            if (tooltip) tooltip.style.display = 'block';
          }}
          onMouseLeave={(e) => {
            const tooltip = e.currentTarget.querySelector('.tooltip-content');
            if (tooltip) tooltip.style.display = 'none';
          }}
        >
          {/* 悬浮按钮 */}
          <button 
            className="p-3 rounded-circle"
            style={{
              backgroundColor: '#d32f2f',
              color: 'white',
              border: 'none',
              cursor: 'pointer',
              boxShadow: '0 0 20px rgba(211, 47, 47, 0.8), 0 4px 16px rgba(0, 0, 0, 0.3)',
              transition: 'all 0.3s ease',
              fontSize: '16px',
              fontWeight: 'bold',
              minWidth: '60px',
              height: '60px',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              zIndex: 9999,
              opacity: 1,
              visibility: 'visible'
            }}
          >
            使用说明
          </button>
          
          {/* 悬停显示的说明内容 */}
          <div 
            className="tooltip-content p-4 rounded-lg fade-in"
            style={{
              position: 'absolute',
              bottom: '70px',
              right: '0',
              backgroundColor: 'rgba(26, 26, 26, 0.9)',
              border: '2px solid #d32f2f',
              color: 'white',
              width: '350px',
              boxShadow: '0 0 20px rgba(211, 47, 47, 0.5), 0 4px 16px rgba(0, 0, 0, 0.3)',
              backdropFilter: 'blur(15px)',
              display: 'none',
              transition: 'opacity 0.3s ease'
            }}
          >
            <h4 style={{color: '#d32f2f', marginBottom: '15px', borderBottom: '1px solid rgba(211, 47, 47, 0.3)', paddingBottom: '10px'}}>使用说明</h4>
            <ol className="list-group list-group-numbered" style={{backgroundColor: 'transparent'}}>
              <li className="list-group-item" style={{backgroundColor: 'rgba(40, 40, 40, 0.5)', borderColor: 'rgba(211, 47, 47, 0.3)', color: 'white'}}>在各个标签页中修改服务器配置</li>
              <li className="list-group-item" style={{backgroundColor: 'rgba(40, 40, 40, 0.5)', borderColor: 'rgba(211, 47, 47, 0.3)', color: 'white'}}>勾选取用功能，取消勾选禁用功能</li>
              <li className="list-group-item" style={{backgroundColor: 'rgba(40, 40, 40, 0.5)', borderColor: 'rgba(211, 47, 47, 0.3)', color: 'white'}}>点击"保存配置"按钮保存更改</li>
              <li className="list-group-item" style={{backgroundColor: 'rgba(40, 40, 40, 0.5)', borderColor: 'rgba(211, 47, 47, 0.3)', color: 'white'}}>使用页面顶部的按钮启动/停止服务器</li>
              <li className="list-group-item" style={{backgroundColor: 'rgba(40, 40, 40, 0.5)', borderColor: 'rgba(211, 47, 47, 0.3)', color: 'white'}}>修改配置后需要重启服务器才能生效</li>
              <li className="list-group-item" style={{backgroundColor: 'rgba(40, 40, 40, 0.5)', borderColor: 'rgba(211, 47, 47, 0.3)', color: 'white'}}>服务器状态会显示在页面顶部</li>
            </ol>
          </div>
        </div>
      </div>
    </Container>
  );
}

export default App;